package com.budwk.app.sqfwV2.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import com.alibaba.fastjson.JSONObject;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.dto.PartyMemberInformation;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.models.Sqfw_form_summary_pdf;
import com.budwk.app.sqfw.services.PartyMemberInformationService;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormSummaryPdfService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowExcelParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelGenerator;
import com.budwk.app.sqfwV2.dto.CaringStaffDTO;
import com.budwk.app.sqfwV2.dto.DifficultPersonDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownFileTypesResVo;
import com.budwk.app.sqfwV2.dto.vo.SummaryQueryReqVo;
import com.budwk.app.sqfwV2.enums.CaringStaffEnum;
import com.budwk.app.sqfwV2.enums.DifficultPersonEnum;
import com.budwk.app.sqfwV2.enums.LandscapePatrolEnum;
import com.budwk.app.sqfwV2.service.SummarySafetyService;
import com.budwk.app.sqfwV2.service.caringStaff.CaringStaffExcelService;
import com.budwk.app.sqfwV2.service.caringStaff.CaringStaffPdfService;
import com.budwk.app.sqfwV2.service.caringStaff.CaringStaffV2ExcelService;
import com.budwk.app.sqfwV2.service.caringStaff.DifficultPersonPdfService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.common.exception.BaseException;
import com.budwk.starter.common.openapi.annotation.ApiDefinition;
import com.budwk.starter.common.openapi.annotation.ApiOperation;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@IocBean
@At("/platform/sqfwV2/difficultPerson")
@ApiDefinition(tag = "困难人员走访")
@Slf4j
public class DifficultPersonController {


    @Inject
    private DifficultPersonPdfService difficultPersonPdfService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;
    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private PartyMemberInformationService partyMemberInformationService;

    @Inject
    private SysOssService sysOssService;
    @Inject
    private SysUserService sysUserService;

    @Inject
    private SummarySafetyService summarySafetyService;








    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "人员列表")
    @SaCheckLogin
    public Result<?> personList(@Param("pageNo") int pageNo,
                                         @Param("pageSize") int pageSize,
                                         @Param("param") String param,
                                         @Param("partyMemberLabel") String partyMemberLabel) {
        Sys_user sysUser=sysUserService.getUserById(SecurityUtil.getUserId());
        Cnd cnd = Cnd.NEW();
        cnd.and(PartyMemberInformation::getCommunity,"=",sysUser.getCommunity())
                .and(PartyMemberInformation::getCounty,"=",sysUser.getCounty())
                .and(PartyMemberInformation::getBusinessType,"like","%"+SupportBusinessTypeEnum.DIFFICULT_PERSON_VISIT.getName()+"%")
                .desc(PartyMemberInformation::getCreateDte);
        if(StrUtil.isNotEmpty(param)){
           cnd.and(Cnd.exps(PartyMemberInformation::getIdNumber,"like",'%'+param+'%').or(Cnd.exps(PartyMemberInformation::getName,"like",'%'+param+'%')));
        }
        if(StrUtil.isNotEmpty(partyMemberLabel)){
            List<String> lab=Arrays.asList(partyMemberLabel.split(","));
            SqlExpressionGroup sql = new SqlExpressionGroup();
            for (String s : lab) {
                sql =sql.or(Cnd.exps("(special_mark::text)","like","%\"key\": \""+s+"\"%"));

            }
            cnd.and(sql);
        }
        Pagination pagination =  partyMemberInformationService.listPage(pageNo,pageSize,cnd);
        pagination.getList(PartyMemberInformation.class).forEach(s->{
            if(IdcardUtil.isValidCard(s.getIdNumber())){
                s.setAge(IdcardUtil.getAgeByIdCard(s.getIdNumber()));
                s.setGender( IdcardUtil.getGenderByIdCard(s.getIdNumber())==1?"男":"女");
            }
        });
        return Result.data(pagination);
    }



    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "困难人员历史记录")
    @SaCheckLogin
    public Result<?> difficultPersonHistoryList(@Param("pageNo") int pageNo,
                                            @Param("pageSize") int pageSize,
                                            @Param("sort") String sort,
                                            @Param("fillDate") String fillDate,
                                                @Param("id") String id) {

        SqlExpressionGroup sql =new SqlExpressionGroup()
                .and("param_data ->>'id'","=",id);
        SummaryQueryReqVo dto = new SummaryQueryReqVo();
        dto.setPageNo(pageNo);
        dto.setPageSize(pageSize);
        dto.setSort(sort);
        dto.setFillDate(fillDate);
        dto.setFillType(SupportBusinessTypeEnum.DIFFICULT_PERSON_VISIT.getName());
        dto.setSqlExpressionGroup(sql);
        return summarySafetyService.listSummaryByPage(dto);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "党员历史记录")
    @SaCheckLogin
    public Result<?> interviewRecord(@Param("pageNo") int pageNo,
                                            @Param("pageSize") int pageSize,
                                            @Param("sort") String sort,
                                            @Param("fillDate") String fillDate,
                                            @Param("partyMemberLabel") String partyMemberLabel) {
        SummaryQueryReqVo dto = new SummaryQueryReqVo();
        dto.setPageNo(pageNo);
        dto.setPageSize(pageSize);
        dto.setSort(sort);
        dto.setFillDate(fillDate);
        dto.setFillType(SupportBusinessTypeEnum.DIFFICULT_PERSON_VISIT.getName());
        if(StrUtil.isNotEmpty(partyMemberLabel)){
            SqlExpressionGroup sql = new SqlExpressionGroup();
            List<String> lab=Arrays.asList(partyMemberLabel.split(","));
            for (String s : lab) {
                sql =sql.or(Cnd.exps("param_data ->>'difficultCategory'","like","%"+s+"%"));
            }
            dto.setSqlExpressionGroup(sql);
        }
        return summarySafetyService.listSummaryByPage(dto);
    }


    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "通过名字模糊查询")
    @SaCheckLogin
    public Result<?> fuzzyQuery(@Param("name") String name) {
        Sys_user sysUser=sysUserService.getUserById(SecurityUtil.getUserId());
        List<PartyMemberInformation>   partyMemberInformations =  partyMemberInformationService.query(Cnd.where(Sqfw_formSummary_new::getProvince,"=",sysUser.getProvince())
                .and(Sqfw_formSummary_new::getCity,"=",sysUser.getCity())
                .and(Cnd.exps(Sqfw_formSummary_new::getDistrict,"=",sysUser.getDistrict()))
                .and(Cnd.exps(Sqfw_formSummary_new::getCounty,"=",sysUser.getCounty()))
                .and(Cnd.exps(Sqfw_formSummary_new::getCommunity,"=",sysUser.getCommunity()))
                .and(PartyMemberInformation::getName,"like","%" + name + "%"));
        List<NutMap>  nutMaps= new ArrayList<>();
        for (PartyMemberInformation partyMemberInformation : partyMemberInformations) {
            nutMaps.add(NutMap.NEW().addv("id",partyMemberInformation.getId())
                    .addv("name",partyMemberInformation.getName()));
        }
        return Result.data(nutMaps);
    }
    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "党员详情")
    @SaCheckLogin
    public Result<?> getDifficultPersonInfo(@Param("id") String id) {
        PartyMemberInformation  partyMemberInformation =  partyMemberInformationService.fetch(id);
        if(ObjectUtil.isEmpty(partyMemberInformation)){
            throw new BaseException("无法找到对象 partyMemberInformation");
        }
        return Result.data(partyMemberInformation);
    }
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "添加人员")
    @SaCheckLogin
    public Result<?>  addPartyMember(@Param("..") PartyMemberInformation partyMemberInformation) {
        Sys_user sysUser=sysUserService.getUserById(SecurityUtil.getUserId());
        BeanUtil.copyProperties(sysUser,partyMemberInformation,"id");
        partyMemberInformation.setCreateBy(sysUser.getId());
        partyMemberInformation.setCreateDte(LocalDateTime.now());
        partyMemberInformation.setBusinessType(SupportBusinessTypeEnum.DIFFICULT_PERSON_VISIT.getName());
        partyMemberInformationService.insert(partyMemberInformation);
        return Result.data(partyMemberInformation);
    }
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "修改人员信息")
    @SaCheckLogin
    public Result<?>  updatePartyMember(@Param("..") PartyMemberInformation partyMemberInformation) {
        PartyMemberInformation update= partyMemberInformationService.fetch(partyMemberInformation.getId());
        if(ObjectUtil.isEmpty(update)){
            throw new BaseException("无法找到对象PartyMemberInformation");
        }
        partyMemberInformation.setUpdateBy(SecurityUtil.getUserId());
        partyMemberInformation.setUpdateDate(LocalDateTime.now());
        partyMemberInformationService.update(Chain.make("name",partyMemberInformation.getName())
                        .add("nation",partyMemberInformation.getNation())
                        .add("address",partyMemberInformation.getAddress())
                        .add("gender",partyMemberInformation.getGender())
                        .add("phone",partyMemberInformation.getPhone())
                        .add("id_number",partyMemberInformation.getIdNumber())
                        .add("birth_date",partyMemberInformation.getDateOfBirth()),
                Cnd.where(PartyMemberInformation::getId, "=", partyMemberInformation.getId()));
        return Result.data(partyMemberInformation);
    }



    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "生成下载页面")
    @SaCheckLogin
    public Result<?> generateDetailFile(@Param("..") SummaryQueryReqVo reqVo) {
        Sys_user sysUser=sysUserService.getUserById(SecurityUtil.getUserId());
        SqlExpressionGroup sql = new SqlExpressionGroup();
        sql.andBetween(Sqfw_formSummary_new::getFillDate, reqVo.getFillStartDate() + " 00:00:00", reqVo.getFillEndDate() + " 23:59:59");
        if(StrUtil.isNotEmpty(reqVo.getQueryKey())){
            sql.and("param_data ->>'id'","=",reqVo.getQueryKey());
        }
        List<Sqfw_formSummary_new> a = sqfwFormsummaryNewService.query(Cnd.where(sysUser.getCommunity().equals("直属")?"county":"community" ,"=",sysUser.getCommunity().equals("直属")?sysUser.getCounty():sysUser.getCommunity())
                .and(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.DIFFICULT_PERSON_VISIT.getName())
                .and(sql));
        List<DownFileTypesResVo> downFileTypesResVos = new ArrayList<>();
        DifficultPersonEnum[] values = DifficultPersonEnum.values();
        for (DifficultPersonEnum serviceEnum : values) {
            DownFileTypesResVo resVo = new DownFileTypesResVo();
            resVo.setFileName(serviceEnum.getFileName())
                    .setPreviewImage(List.of(serviceEnum.getPreviewImage().split(",")))
                    .setFileCode(String.valueOf(serviceEnum.getCode()))
                    .setCreatedAt(System.currentTimeMillis())
                    .setLocation(serviceEnum.getCode());
            if (serviceEnum.getCode() == 1) {
                resVo.setFileType("pdf");
                resVo.setLabel("走访记录");
                if (a.size() > 0) {
                    resVo.setHiveData(true);
                }
                downFileTypesResVos.add(resVo);
            }
        }
        Pagination pagination = new Pagination();
        pagination.setList(downFileTypesResVos);
        pagination.setTotalCount(a.size());
        return Result.data(pagination);
    }






    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "下载pdf")
    @SaCheckLogin
    public Result<?> downPdfLedgerV2(@Param("..") DownExcelLedgerReqVo reqVo) {
        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
        generateExcelUrlVOS.add(generateExcelUrlVO);
        Integer code=Integer.valueOf(reqVo.getFileCode());
        Sys_user sysUser=sysUserService.getUserById(SecurityUtil.getUserId());
        if (reqVo.isDownTemplate()) {
            String filePath = DifficultPersonEnum.getBlankTemplate(code) ;
            String fileName =filePath.substring(filePath.lastIndexOf("/")+1);
            generateExcelUrlVO.setExcelUrl( sysOssService.upload( CommonFormOfficeUtils.getTempPdfFile(filePath),fileName).getUrl());
        } else {
            SqlExpressionGroup sql = new SqlExpressionGroup();
            sql.and(sysUser.getCommunity().equals("直属")?"county":"community" ,"=",sysUser.getCommunity().equals("直属")?sysUser.getCounty():sysUser.getCommunity());
            if(StrUtil.isNotEmpty(reqVo.getQueryKey())){
                sql.and("param_data ->>'id'","=",reqVo.getQueryKey());
            }
            List<Sqfw_formSummary_new>  formSummaryList = sqfwFormsummaryNewService.query(Cnd.where(
                    Sqfw_formSummary_new::getFillDate,"between",new Object[]{reqVo.getFillStartDate() + " 00:00:00", reqVo.getFillEndDate() + " 23:59:59"})
                            .and(Sqfw_formSummary_new::getType,"=",SupportBusinessTypeEnum.DIFFICULT_PERSON_VISIT.getName())
                            .and(sql)
                            .desc(Sqfw_formSummary_new::getCreateDate));
            if (CollectionUtil.isNotEmpty(formSummaryList)) {
                Map<String,List<Sqfw_formSummary_new>>   map =   formSummaryList.stream().collect(Collectors.groupingBy(s-> JSONObject.parseObject(s.getParamData(), DifficultPersonDTO.class).getId()));
                List<String> summaryIdS = new ArrayList<>();
                for (String s : map.keySet()) {
                    List<Sqfw_formSummary_new> sqfwFormSummaryNews =   map.get(s);
                    summaryIdS.add(sqfwFormSummaryNews.get(0).getSqfwFlowId());
                }
                List<Sqfw_completeflow>  completeflow= sqfwCompleteflowService.query(Cnd.where(Sqfw_completeflow::getId, "in", summaryIdS)
                        .and(Sqfw_completeflow::getResourcePath, "!=", "creating")
                        .and(Sqfw_completeflow::getResourcePath, "!=", "error"));
                if (CollectionUtil.isNotEmpty(completeflow)) {
                    List<String> pdfPathList = completeflow.stream().map(Sqfw_completeflow::getResourcePath).collect(Collectors.toList());
                    String url = CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, DifficultPersonEnum.getFileName(code));
                    generateExcelUrlVO.setExcelUrl(url);
                }
            }
        }
        return Result.data( generateExcelUrlVOS);
    }

}
